package com.kykj.kykj.controller;

import com.kykj.kykj.entity.ResultEntity;
import com.kykj.kykj.entity.UserEntity;
import com.kykj.kykj.service.UserService;
import com.kykj.kykj.service.impl.TokenServiceImpl;
import com.kykj.kykj.service.impl.UserServiceImpl;
import com.kykj.kykj.tool.KoDoTool;
import com.kykj.kykj.vo.UserVo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.UUID;

@RequestMapping("v2/user/")
@CrossOrigin//解决跨域问题
@RestController
public class UserController {
    @Resource
    UserServiceImpl userService;
    @Resource
    TokenServiceImpl tokenService;

    @Value("${project.localfilepath}")
    private String localFilePath;//本地保存文件路径

    @Resource
    KoDoTool koDoTool;//注入KodDoTool
    /**
     * 获取用户列表页
     * @return JSON
     */
    @GetMapping("getuserlist")
    private ResultEntity getUserList(){
        ResultEntity resultEntity = new ResultEntity();
        try{
            resultEntity.setData(userService.getUserList());
            resultEntity.setCode(0);
            resultEntity.setMsg("数据获取成功！");
        }catch (Exception e){
            resultEntity.setCode(-1);
            resultEntity.setMsg("系统错误");
        }
        return  resultEntity;
    }

    /**
     * 新增用户
     * @param userVo 用户对象
     * @return JSON
     */
    @PostMapping("user")
    private ResultEntity addUser(@RequestBody UserVo userVo){
        ResultEntity resultEntity = new ResultEntity();
        try{

            if(userService.addUser(userVo)>0){
                System.out.println("当前自增的id是"+userVo.getUid()+"------自增");
                resultEntity.setCode(0);
                resultEntity.setMsg("添加成功！");
            }else{
                resultEntity.setCode(1);
                resultEntity.setMsg("添加失败！"+userVo.getUid());
            }
        }catch (Exception e){
            e.printStackTrace();
            resultEntity.setCode(-1);
            resultEntity.setMsg("系统错误");
        }
        return  resultEntity;
    }

    /**
     * 更新用户信息
     * @param userVo 用户对象
     * @return JSON
     */
    @PutMapping("user")
    private ResultEntity upUser(@RequestBody UserVo userVo){
        ResultEntity resultEntity = new ResultEntity();
        try{
            if(userService.upUser(userVo)>0){
                resultEntity.setCode(0);
                resultEntity.setMsg("修改成功！");
            }else{
                resultEntity.setCode(1);
                resultEntity.setMsg("修改失败！");
            }
        }catch (Exception e){
            resultEntity.setCode(-1);
            resultEntity.setMsg("系统错误");
        }
        return  resultEntity;
    }

    /**
     * 删除用户
     * @param uid 用户id
     * @return JSON
     */
    @DeleteMapping("user/{uid}")
    private ResultEntity delUser(@PathVariable("uid") int uid){
        ResultEntity resultEntity = new ResultEntity();
        try{
            if(uid==1){
                resultEntity.setCode(2);
                resultEntity.setMsg("管理员不允许删除！");
            }else{
                if(userService.delUser(uid)>0){
                    resultEntity.setCode(0);
                    resultEntity.setMsg("删除成功！");
                }else{
                    resultEntity.setCode(1);
                    resultEntity.setMsg("删除失败！");
                }
            }
        }catch (Exception e){
            resultEntity.setCode(-1);
            resultEntity.setMsg("系统错误");
        }
        return  resultEntity;
    }

    /**
     * 获取用户列表
     * @param page 页码
     * @param limit 每页行数
     * @param uname 用户名
     * @return JSON
     */
    @GetMapping("user")
    private ResultEntity getUserByPage(
            @RequestParam("page") int page,
            @RequestParam("limit") int limit,
            @RequestParam("uname") String uname
            ){
        ResultEntity resultEntity = new ResultEntity();
        try{
            int start =(page-1)*limit;
            int cnt=-1;
            List<UserEntity> list = userService.getUserByPage(uname,start,limit);
            if(!uname.equals("")){
                cnt=list.size();//有查询条件的时候，就按查询回来的条数计
            }else{
                cnt= userService.getUserCount();//当没有查询条件的时候 就获取所有用户数量
            }
            resultEntity.setCode(0);
            resultEntity.setMsg("数据获取成功！");
            resultEntity.setData(list);
            resultEntity.setCount(cnt);
        }catch (Exception exception){
            exception.printStackTrace();
            resultEntity.setCode(-1);
            resultEntity.setMsg("系统错误");
        }
        return resultEntity;
    }

    /**
     * 登录
     * @param uname 用户名
     * @param upwd 密码
     * @return ResultEntity
     */
    @GetMapping("dologin")
    private ResultEntity dologin(
            @RequestParam("uname") String uname,
            @RequestParam("upwd") String upwd
    ){
        ResultEntity resultEntity = new ResultEntity();
        UserEntity userEntity = new UserEntity();
        userEntity=userService.doLogin(uname, upwd);
        /*存储对象*/
        UserEntity safeUser = new UserEntity();
        if(uname.equals("") || upwd.equals("")){
            resultEntity.setCode(-9999);
            resultEntity.setMsg("用户名或密码为空");
        }else{
            if(userService.doLogin(uname, upwd)!=null){//登录成功
                safeUser.setUid(userEntity.getUid());
                safeUser.setUname(userEntity.getUname());
                safeUser.setUphone(userEntity.getUphone());
                safeUser.setAvatar(userEntity.getAvatar());
                resultEntity.setCode(0);
                resultEntity.setMsg("登录成功！");
                resultEntity.setData(tokenService.createToken(uname));//生成token并存入redis
                tokenService.createUserToken(uname,safeUser);
            }else{
                resultEntity.setCode(-1);
                resultEntity.setMsg("登录失败，无法获取Token");
            }
        }
        return resultEntity;
    }

    /**
     * 退出登录（Token失效）
     * @param uname 用户名
     * @return ResultEntity
     */
    @GetMapping("exit")
    private ResultEntity exitLogin(@RequestParam("uname") String uname){
        ResultEntity resultEntity = new ResultEntity();
        try{
            if(tokenService.delToken(uname)){
                resultEntity.setCode(0);
                resultEntity.setMsg("退出登录成功！");
            }else{
                resultEntity.setCode(1);
                resultEntity.setMsg("退出登录失败！");
            }
        }catch (Exception e){
            resultEntity.setCode(-1);
            resultEntity.setMsg("退出登录失败！");
        }
        return resultEntity;
    }


    /**
     * 根据token获取用户信息
     * @param token
     * @return resultEntity
     */
    @GetMapping("getUserInfo")
    private ResultEntity getUserInfo(
            @RequestHeader("token") String token  // 从请求头获取 token
    ) {
        ResultEntity resultEntity = new ResultEntity();
        if (token == null || token.isEmpty()) {
            resultEntity.setCode(-9999);
            resultEntity.setMsg("Token不能为空");
            return resultEntity;
        }
        UserEntity userEntity = tokenService.getUserByToken(token);
        if (userEntity != null) {
            resultEntity.setCode(0);
            resultEntity.setMsg("获取用户信息成功");
            resultEntity.setData(userEntity);  // 返回用户实体数据
        } else {
            resultEntity.setCode(-2);  // 区别于登录的-1
            resultEntity.setMsg("无效Token或用户信息已过期");
        }

        return resultEntity;
    }

    /**
     * 修改头像
     * @param multipartFile 文件
     * @param uid 用户id
     * @return resultEntity
     */
    @PostMapping("upAvatar")
    private ResultEntity upAvatar(@RequestParam("avatar") MultipartFile multipartFile, @RequestParam("uid") int uid ){
        ResultEntity resultEntity=new ResultEntity();
        if(! new File(localFilePath).exists()){//如果文件夹不存在
            if(! new File(localFilePath).mkdir()){
                resultEntity.setCode(3);
                resultEntity.setMsg("文件夹创建失败！！");
                return resultEntity;
            }
        }
        String sufName=multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));//获取文件后缀名后缀名
        String fileName= UUID.randomUUID().toString()+sufName;//生成新的文件名
        String pathFileName=localFilePath+fileName;//本地文件保存的全路径
        File dest=new File(pathFileName);//生成文件对象
        try {
            multipartFile.transferTo(dest);//保存文件
            String KoDoUrl=koDoTool.UpLoadFile(pathFileName);//上传文件到七牛云
            if (koDoTool==null){
                resultEntity.setCode(-1);
                resultEntity.setMsg("文件上传云端失败！");
            }
            else {
                if (userService.upAvatar(KoDoUrl,uid)==0){
                    resultEntity.setCode(-2);
                    resultEntity.setMsg("文件上传数据库失败！");
                }else {
                    resultEntity.setCode(0);
                    resultEntity.setMsg("头像上传成功！"+"");
                }
            }
        } catch (Exception e) {
            resultEntity.setCode(-9999);
            resultEntity.setMsg("文件上传失败！");
            e.printStackTrace();
        }
        return resultEntity;


    }
}
